package com.leyou;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.vo.PageResult;
import com.leyou.dto.SkuDTO;
import com.leyou.dto.SpecParamDTO;
import com.leyou.dto.SpuDTO;
import com.leyou.dto.SpuDetailDTO;
import com.leyou.item.client.ItemClient;
import com.leyou.search.domain.Goods;
import com.leyou.search.mapper.GoodsRepository;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class test {

    @Autowired
    private GoodsRepository repository;
    @Autowired
    private ItemClient  itemClient;

    @Test
    public void buildGoods(){
        //循环查询 所有数据库的数据
        PageResult<SpuDTO> result = itemClient.querySpuByPage(1, 5, null, null);
        //拿到所需要的数据 spu 数据集合
        List<SpuDTO> items = result.getItems();
        for (SpuDTO item : items) {
            //循环 遍历
            //all字段
            String all= item.getCategoryName()+item.getBrandName()+item.getName();
            //id
            Long id = item.getId();
            //促销信息
            String subTitle = item.getSubTitle();
            //skus
            //准备一个list<map> 存储 spu中的每个sku的信息
            List<Map<String,Object>> skusList = new ArrayList<>();


            // 高亮字段 sputitle
            //准备一个 list 存贮高亮信息
            List<String>  spuTitleList = new ArrayList<>();

            //价格Set<Long>
            Set<Long> price = new HashSet<>();
            //通过id查询 sku集合
            List<SkuDTO> skus = itemClient.findSkuById(item.getId());
            for (SkuDTO skuDTO : skus) {
                //准备一个map集合 存储skus集合下每个对象的所需要的字段
                Map<String,Object> maps = new HashMap<>();
                maps.put("id",skuDTO.getId());
                maps.put("title",skuDTO.getTitle()); // 这里是每个sku的特有属性
                maps.put("price",skuDTO.getPrice());
                maps.put("image", StringUtils.substringBefore(skuDTO.getImages(),","));
                skusList.add(maps);

                String name = item.getName();
                String spuTitle = name + skuDTO.getTitle().replace(name,"");
                spuTitleList.add(spuTitle);

                price.add(skuDTO.getPrice());
            }
            //brandid
            Long brandId  = item.getBrandId();
            //categoryId
            Long categoryId = item.getCategoryIds().get(item.getCategoryIds().size()-1);
            //createTime
            Long createTime  = item.getCreateTime().getTime();
            //specs 包括通用属性 和 特有属性
            //规格参数
            Map<String,Object> specsMap = new HashMap<>();
            List<SpecParamDTO> params = itemClient.querySpecParams(null, categoryId, true);
            SpuDetailDTO spuDetailDTO = itemClient.findSpuDetailById(item.getId());
            Map<Long, Object> genericSpec = JsonUtils.toMap(spuDetailDTO.getGenericSpec(), Long.class, Object.class);
            //特有属性
            Map<Long, List<String>> specialSpec= JsonUtils.nativeRead(spuDetailDTO.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
            });
            for (SpecParamDTO specParamDTO : params) {
                //获取规格参数的名称
                String name = specParamDTO.getName();
                //获取规格参数值
                Object value = null;
                //判断是否是通用规格
                if(specParamDTO.getGeneric()){
                    //通用
                    value = genericSpec.get(specParamDTO.getId());
                }else{
                    //特有
                    value = specialSpec.get(specParamDTO.getId());
                }
                //判断是否是数组类型
                if(specParamDTO.getNumeric()){
                    value = chooseSegment(value,specParamDTO);
                }
                specsMap.put(name,value);

            }

            Goods good = new Goods();
            good.setId(item.getId());
            good.setSubTitle(subTitle);
            good.setSkus(JsonUtils.toString(skusList));
            good.setSpuTitle(JsonUtils.toString(spuTitleList));
            good.setAll(all);
            good.setBrandId(brandId);
            good.setCategoryId(categoryId);
            good.setCreateTime(createTime);
            good.setPrice(price);
            good.setSpecs(specsMap);
            System.out.println(JsonUtils.toString(good));
        }

    }

    private String chooseSegment(Object value, SpecParamDTO p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }


}
